﻿//判断是否支持indexedDB
var indexedDB = window.indexedDB || widow.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
if (!indexedDB) {
	console.log("你的浏览器不支持IndexedDB");
}



//添加数据方法
function add(str,db) {
	var re = db.transaction(['questions'], 'readwrite')//创建一个事务，具有读写权限
		.objectStore('questions')
		.add(str);
	//获取objectStore，再调用add方法添加数据
	re.onsuccess = function (e) {
		console.log('数据写入成功');
		db.close();
	};
}

//读取数据
function read(index, item, action) {
	var db;
	var request = indexedDB.open('questions', 3);//打开数据库
	request.onerror = function (e) {//打开错误事件
		console.log(e.currentTarget.error.message);
	};
	request.onsuccess = function (e) {//打开成功事件
		db = e.target.result;
		console.log('成功打开DB');

		var re = db.transaction(['questions']);
		var objectStore = re.objectStore('questions');
		var request = objectStore.get(index);//用于获取数据

		request.onerror = function (event) {
			console.log('读取失败');
		};
		request.onsuccess = function (event) {
			if (request.result) {
				if (action === 'add') {//更新操作
					update(item,db);
				} else if (action === 'remove') {//移除操作
					remove(index,db);
				}
			} else {
				add(item,db);//添加操作
			}
		};
	};

	request.onupgradeneeded = function (e) {//指定的版本号，大于数据库的实际版本号，就会发生数据库升级事件upgradeneeded。
		db = e.target.result;
		if (!db.objectStoreNames.contains('questions')) {
			//如果表格不存在，创建一个新的表格（keyPath，主键；autoIncrement，是否自增），会返回一个对象（objectStore）
			var objectStore = db.createObjectStore('questions', {
				keyPath: "QuestionIndex"
			});
		}
	}
	
}

//遍历数据，要使用指针对象IDBCursor
async function readAll() {
	var db;
	var request = indexedDB.open('questions', 3);//打开数据库
	request.onerror = function (e) {//打开错误事件
		console.log(e.currentTarget.error.message);
	};
	request.onsuccess = async function (e) {//打开成功事件
		db = e.target.result;
		console.log('成功打开DB');

		let tx = db.transaction('questions', 'readonly');
		let store = tx.objectStore('questions');
		let allSavedItems = await store.getAll();
		allSavedItems.onsuccess = function () {
			var questions, single = [], blank = [], tureFlase = [];
			var data = allSavedItems.result;
			for (var a in data) {
				//console.log(data[a]);
				if (data[a].QuestType == 1) {
					single.push(data[a]);
				} else if (data[a].QuestType == 2) {
					tureFlase.push(data[a]);
				} else if (data[a].QuestType == 3) {
					blank.push(data[a]);
				}
			}
			questions = { Singles: single, Blanks: blank, TureFlases: tureFlase };
			var jsonStr = JSON.stringify(questions);
            var loading = layer.msg('保存中',
                {
                    icon: 16,
                    time: 5000,
                    shade: 0.1
                });
            $.ajax({
                type: "post",
                url: "/Main/SaveResult",
                dataType: 'text',
                data: {
                    jsonstr: jsonStr
                },
                success: function(data) {
					removeAll(db);
                    layer.close(loading);
                },
                error: function(data) {
					layer.msg(data.msg);
                    layer.close(loading);
                }
            });
        }
	};
	request.onupgradeneeded = function (e) {//指定的版本号，大于数据库的实际版本号，就会发生数据库升级事件upgradeneeded。
		db = e.target.result;
		if (!db.objectStoreNames.contains('questions')) {
			//如果表格不存在，创建一个新的表格（keyPath，主键；autoIncrement，是否自增），会返回一个对象（objectStore）
			var objectStore = db.createObjectStore('questions', {
				keyPath: "QuestionIndex"
			});
		}
	}
}

//更新数据，使用IDBObject.put()
function update(str,db) {
	var request = db.transaction(['questions'], 'readwrite')
		.objectStore('questions')
		.put(str);

	request.onsuccess = function (event) {
		console.log('更新成功');
		db.close();
	}
	request.onerror = function (event) {
		console.log('数据更新失败');
		db.close();
	}
}

//删除记录,IDBObjectStore.delete()方法用于删除记录。
function remove(key,db) {
	var request = db.transaction(['questions'], 'readwrite')
		.objectStore('questions')
		.delete(key);

	request.onsuccess = function (event) {
		console.log('数据删除成功');
		db.close();
	};
}

//删除全部数据
async function removeAll(db) {
	let tx = db.transaction('questions', 'readwrite').objectStore('questions');
	let allItems = await tx.getAll();
	allItems.onsuccess = function () {
		var allIndex = allItems.result;
		for (var a in allIndex) {
			//remove(allIndex[a].QuestionIndex);
			var request = db.transaction(['questions'], 'readwrite')
				.objectStore('questions')
				.delete(allIndex[a].QuestionIndex);
		}
		db.close();
    }
}

//关闭数据库
function closeDB() {
	db.close();
}
//删除数据库
function deleteDB(name) {
	indexedDB.deleteDatabase(name);
}